package _022_2_12

func SpiralOrder(matrix [][]int) []int {
	visited := make([][]int, len(matrix))
	result := make([]int, 0)
	for row := 0; row < len(visited); row++ {
		for cell := 0; cell < len(visited); cell++ {
			visited[row] = append(visited[row], 0)
		}
	}
	direct := 0
	visitedNum := 0
	cell, row := 0, 0

	for visitedNum < len(matrix)*len(matrix) {
		if direct == 0 {
			for ; cell < len(visited) && visited[row][cell] != 1; cell++ {
				result = append(result, matrix[row][cell])
				visited[row][cell] = 1
				visitedNum++
			}
			cell--
			row++
			direct = 1

		} else if direct == 1 {
			for ; row < len(visited) && visited[row][cell] != 1; row++ {
				result = append(result, matrix[row][cell])
				visited[row][cell] = 1
				visitedNum++
			}
			row--
			cell--
			direct = 2

		} else if direct == 2 {
			for ; cell >= 0 && visited[row][cell] != 1; cell-- {
				result = append(result, matrix[row][cell])
				visited[row][cell] = 1
				visitedNum++
			}

			cell++
			row--
			direct = 3
		} else if direct == 3 {
			for ; row >= 0 && visited[row][cell] != 1; row-- {
				result = append(result, matrix[row][cell])
				visited[row][cell] = 1
				visitedNum++
			}

			row++
			cell++
			direct = 0
		}
	}

	return result

}
